<template>
  <div class="api-management-container">
    <el-card class="search-card">
      <div class="search-section">
        <div class="search-left">
          <el-input
            v-model="queryParams.search"
            placeholder="请输入API名称或描述"
            style="width: 300px; margin-right: 10px"
            clearable
            @keyup.enter="fetchApiList"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" @click="fetchApiList">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><RefreshRight /></el-icon>
            重置
          </el-button>
        </div>
        <div class="search-right">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增API
          </el-button>
        </div>
      </div>
    </el-card>

    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="apiList"
        style="width: 100%"
        stripe
        border
      >
        <el-table-column prop="function_name" label="API名称" width="200" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="endpoint_url" label="接口地址" show-overflow-tooltip />
        <el-table-column prop="http_method" label="请求方法" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getMethodType(row.http_method)"
              size="small"
            >
              {{ row.http_method }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="required_params" label="必需参数" width="150">
          <template #default="{ row }">
            <el-tag
              v-for="param in (row.required_params || []).slice(0, 2)"
              :key="param"
              size="small"
              style="margin-right: 5px"
            >
              {{ param }}
            </el-tag>
            <span v-if="(row.required_params || []).length > 2" class="more-params">
              +{{ (row.required_params || []).length - 2 }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="intent_keywords" label="意图关键词" width="150">
          <template #default="{ row }">
            <el-tag
              v-for="keyword in (row.intent_keywords || []).slice(0, 2)"
              :key="keyword"
              type="info"
              size="small"
              style="margin-right: 5px"
            >
              {{ keyword }}
            </el-tag>
            <span v-if="(row.intent_keywords || []).length > 2" class="more-params">
              +{{ (row.intent_keywords || []).length - 2 }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(row)"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="handleTest(row)"
            >
              <el-icon><Connection /></el-icon>
              测试
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- API配置表单对话框 -->
    <api-form
      v-model="formDialogVisible"
      :form-data="formData"
      :is-add="isAdd"
      @success="fetchApiList"
    />

    <!-- API测试对话框 -->
    <api-test
      v-model="testDialogVisible"
      :api-config="selectedApi"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import {
  Plus,
  Edit,
  Delete,
  Search,
  RefreshRight,
  Connection,
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import ApiForm from './components/ApiForm.vue'
import ApiTest from './components/ApiTest.vue'
import { getAllApiFunctions, deleteApiFunction, toggleApiFunction } from '@/api/external-api'

// 定义组件名
defineOptions({
  name: 'ExternalApiPage',
})

// 状态
const apiList = ref([])
const loading = ref(false)
const formDialogVisible = ref(false)
const testDialogVisible = ref(false)
const selectedApi = ref(null)
const isAdd = ref(true)

// 查询参数
const queryParams = reactive({
  search: '',
  skip: 0,
  limit: 10,
})

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
})

// 表单数据
const formData = reactive({
  id: null,
  task_config_id: '',
  function_name: '',
  description: '',
  endpoint_url: '',
  http_method: 'POST',
  headers: {},
  auth_config: {},
  parameters_schema: {},
  required_params: [],
  intent_keywords: [],
  intent_examples: [],
})

// 获取请求方法标签类型
const getMethodType = (method) => {
  const typeMap = {
    GET: 'success',
    POST: 'primary',
    PUT: 'warning',
    DELETE: 'danger',
    PATCH: 'info',
  }
  return typeMap[method] || 'info'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 获取API列表
const fetchApiList = async () => {
  loading.value = true
  try {
    const params = {
      skip: queryParams.skip,
      limit: queryParams.limit,
      search: queryParams.search
    }
    const response = await getAllApiFunctions(params)
    apiList.value = response.data.items || []
    pagination.total = response.data.total || 0
  } catch (error) {
    console.error('获取API列表失败:', error)
    ElMessage.error('获取API列表失败: ' + (error.message || '未知错误'))
    apiList.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  queryParams.search = ''
  pagination.currentPage = 1
  fetchApiList()
}

// 新增API
const handleAdd = () => {
  Object.assign(formData, {
    id: null,
    task_config_id: '',
    function_name: '',
    description: '',
    endpoint_url: '',
    http_method: 'POST',
    headers: {},
    auth_config: {},
    parameters_schema: {},
    required_params: [],
    intent_keywords: [],
    intent_examples: [],
  })
  isAdd.value = true
  formDialogVisible.value = true
}

// 编辑API
const handleEdit = (row) => {
  Object.assign(formData, {
    id: row.id,
    task_config_id: row.task_config_id || '',
    function_name: row.function_name,
    description: row.description || '',
    endpoint_url: row.endpoint_url,
    http_method: row.http_method,
    headers: row.headers || {},
    auth_config: row.auth_config || {},
    parameters_schema: row.parameters_schema || {},
    required_params: row.required_params || [],
    intent_keywords: row.intent_keywords || [],
    intent_examples: row.intent_examples || [],
  })
  isAdd.value = false
  formDialogVisible.value = true
}

// 测试API
const handleTest = (row) => {
  selectedApi.value = row
  testDialogVisible.value = true
}

// 删除API
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除API "${row.function_name}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        await deleteApiFunction(row.id)
        ElMessage.success('删除成功')
        fetchApiList()
      } catch (error) {
        console.error('删除失败:', error)
        ElMessage.error('删除失败: ' + (error.message || '未知错误'))
      }
    })
    .catch(() => {})
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  queryParams.limit = size
  queryParams.skip = 0
  fetchApiList()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  queryParams.skip = (page - 1) * pagination.pageSize
  fetchApiList()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchApiList()
})
</script>

<style scoped>
.api-management-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-left {
  display: flex;
  align-items: center;
}

.search-right {
  display: flex;
  align-items: center;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.more-params {
  color: #909399;
  font-size: 12px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-button + .el-button) {
  margin-left: 8px;
}
</style>